package DMSXL._2024.BinaryTrees;

public class trimBST {
    public static void main(String[] args) {
        Integer[] nums = {3,1,4,null,2};
        TreeNode root = CreateTree.createBinaryTree(nums,0);
        new trimBST().trimBST(root,1,2);
    }
    public TreeNode trimBST(TreeNode root, int low, int high) {
        if(root == null){
            return root;
        }
        if(root.val < low || root.val > high){
            root = deleteNode(root,root.val);
            if(root == null){
                return root;
            }
        }
        root.left = trimBST(root.left,low,high);
        root.right = trimBST(root.right,low,high);
        return root;
    }

    public TreeNode deleteNode(TreeNode root, int key) {
        if (root.left == null) {
            return root.right;
        } else if (root.right == null) {
            return root.left;
        } else {
            TreeNode cur = root.right;
            while (cur.left != null) {
                cur = cur.left;
            }
            cur.left = root.left;
            root = root.right;
            return root;
        }
    }


}
